<template>
  <div>
    <form action="/">
      <van-search
        v-model.trim="keyWords"
        background="#3396fc"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShowResult = false"
      />
    </form>
    <!-- 搜索历史-建议-结果 -->
    <component 
    :keywords="keyWords" 
    :is="componentName"
    @update-keywords="onSearch"
    />
  </div>
</template>

<script>
import SearchHistory from "./components/SearchHistory.vue";
import SearchSuggestions from "./components/SearchSuggestions.vue";
import SearchResult from "./components/SearchResult.vue";

import { mapMutations , mapState } from 'vuex'

export default {
  data() {
    return {
      keyWords: "",
      isShowResult: false, //记录是否触发搜索事件
    };
  },

  components: {
    SearchHistory,
    SearchSuggestions,
    SearchResult,
  },

  computed: {

    ...mapState(['histories']),
    
    componentName() {
      //1.没有搜索内容时 显示搜索历史
      if (this.keyWords === "") {
        return "SearchHistory";
      }

      if (this.isShowResult) {
        return "SearchResult";
      }
      //1.有搜索内容时 显示建议
      return "SearchSuggestions";
    },
  },

  methods: {

    ...mapMutations(['SET_HISTORIES']),

    onSearch(val) {
      // this.isShowResult = true;
      //1.更新keywords
      this.keyWords = val

      //2.存在vuex
      let newHistories = [this.keywords, ...this.histories]

      //3.去重
      newHistories = [...new Set(newHistories)]

      this.SET_HISTORIES(newHistories)

      //4.展示搜索结果
      this.isShowResult = true
    },

    //有问题 稍后解决
    onCancel() {
      // this.$toast("取消");
      // Toast('取消');

      if (this.keyWords === '') {
        console.log("1111");
        //返回上一页
        //this.$router.back()
         this.$router.go(-1)
      } else {
        this.keyWords = ''
      }
    },


  },
};
</script>

<style scoped lang="less">
.van-search__action {
  color: aliceblue;
}
</style>